import com.google.gson.Gson;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.ShardedJedisPool;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

public class RedisOUTUtil {
    public static JedisPool jedisPool = null;
    // Redis服务器IP
    private static String ADDR = ToConfigure.OUTIP;
    // Redis的端口号
    private static int PORT = ToConfigure.OUTPORT;
    // 访问密码
    private static String AUTH = ToConfigure.OUTAUTH;

    static JedisPoolConfig config = new JedisPoolConfig();
    /**
     * 初始化Redis连接池
     */
    static {
        try {
            // 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
            config.setBlockWhenExhausted(true);
            // 设置的逐出策略类名, 默认DefaultEvictionPolicy(当连接超过最大空闲时间,或连接数超过最大空闲连接数)
            config.setEvictionPolicyClassName("org.apache.commons.pool2.impl.DefaultEvictionPolicy");
            // 是否启用pool的jmx管理功能, 默认true
            config.setJmxEnabled(true);
            // 最大空闲连接数, 默认8个 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例。
            config.setMaxIdle(8);
            // 最大连接数, 默认8个
            config.setMaxTotal(200);
            // 表示当borrow(引入)一个jedis实例时，最大的等待时间，如果超过等待时间，则直接抛出JedisConnectionException；
            config.setMaxWaitMillis(1000 * 100);
            // 在borrow一个jedis实例时，是否提前进行validate操作；如果为true，则得到的jedis实例均是可用的；
            config.setTestOnBorrow(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取Jedis实例
     *
     * @return
     */
    public synchronized static Jedis getJedis() {
        try {
            if (jedisPool != null) {
                Jedis resource = jedisPool.getResource();
                return resource;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 释放jedis资源
     *
     * @param jedis
     */
    public static void close(final Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }
    public static void main(String[] args) {
        for(int i = 0;i<=ToConfigure.DBNUM;i++){
            jedisPool = new JedisPool(config, ADDR, PORT, 3000,AUTH,i);
            Jedis jedis = getJedis();
            String value = null;
            Map<String, String> map = null;
            Set<String> keys = jedis.keys("*");
            Iterator<String> it = keys.iterator();
            while (it.hasNext()){
                String key = it.next();
                String type = jedis.type(key);
                String path = "";
                if(type.equalsIgnoreCase("string")){
                    value = jedis.get(key);
                    path = ToConfigure.PATH+"\\"+i+"#"+"@"+"string"+"@"+key+".txt";
                    backups(path,value);
                }
                if(type.equalsIgnoreCase("hash")){
                    map = jedis.hgetAll(key);
                    String json = new Gson().toJson(map);
                    path =  ToConfigure.PATH+"\\"+i+"#"+"@"+"hash"+"@"+key+".txt";
                    backups(path,json);
                }
                if(type.equalsIgnoreCase("set")){
                    Set<String> set = jedis.smembers(key);

                    //使用迭代  取出set对象里面的值放到list里面，再把list转为String。
                    Iterator<String> IT = set.iterator();
                    List<String> list = new ArrayList<String>();
                    while(IT.hasNext()){
                        String s4 = IT.next();
                        list.add(s4);
                        System.out.println("s4:"+s4);
                    }
                    //list对象转换为String 对象
                    StringBuilder result = new StringBuilder();
                    boolean first = true;
                    //第一个前面不拼接","
                    for(String string :list) {
                        if(first) {
                            first=false;
                        }else{
                            result.append(",");
                        }
                        result.append(string);
                    }
                    String str = result.toString();

                    path =  ToConfigure.PATH+"\\"+i+"#"+"@"+"set"+"@"+key+".txt";
                    backups(path,str);
                }
                if(type.equalsIgnoreCase("list")){
                    long in =jedis.llen(key);
                    List<String> list = jedis.lrange(key,0,in);
                    //list对象转换为String 对象
                    StringBuilder result = new StringBuilder();
                    boolean first = true;
                    //第一个前面不拼接","
                    for(String string :list) {
                        if(first) {
                            first=false;
                        }else{
                            result.append(",");
                        }
                        result.append(string);
                    }
                    String str = result.toString();

                    path =  ToConfigure.PATH+"\\"+i+"#"+"@"+"list"+"@"+key+".txt";
                    backups(path,str);
                }
                System.out.println("key:"+key+"类型："+type);
            }
        }
        if(ToConfigure.flag){
            copyToRedisImpl co = new copyToRedisImpl();
            co.run();
        }

    }
    public static void backups(String file, Object o) {
        try {
            FileOutputStream outStream = new FileOutputStream(file);
            outStream.write(o.toString().getBytes());
            outStream.close();
            System.out.println("successful");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
